﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI.WebControls;
using System.Globalization;

namespace HeroldIT.Dnn.Modules.WebControls
{
    /// <summary>
    /// A control for choosing an image in the portal.
    /// </summary>
    public class ImageBrowser : FileBrowser
    {
        #region constants

        private const string DefaultPreviewImage = "~/images/thumbnail.jpg";

        #endregion

        #region control fields

        /// <summary>
        /// Holds the preview image control.
        /// </summary>
        protected Image imgPreview;

        #endregion

        #region properties

        /// <summary>
        /// Gets or sets the filename filter for the file browser.
        /// </summary>
        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override string Filters
        {
            get
            {
                return "image";
            }
            set
            {
            }
        }

        private Unit maxPreviewWidth = 150;

        /// <summary>
        /// Gets or sets the maximum width of the preview image.
        /// </summary>
        public Unit MaxPreviewWidth
        {
            get { return this.maxPreviewWidth; }
            set { this.maxPreviewWidth = value; }
        }

        private Unit maxPreviewHeight = 150;

        /// <summary>
        /// Gets or sets the maximum height of the preview image.
        /// </summary>
        public Unit MaxPreviewHeight
        {
            get { return this.maxPreviewHeight; }
            set { this.maxPreviewHeight = value; }
        }

        private string defaultPreviewImageUrl = DefaultPreviewImage;

        /// <summary>
        /// Gets or sets the default image url for the preview image.
        /// </summary>
        public string DefaultPreviewImageUrl
        {
            get { return this.defaultPreviewImageUrl; }
            set { this.defaultPreviewImageUrl = value; }
        }

        #endregion

        #region constructors

        /// <summary>
        /// Creates a new <see cref="ImageBrowser"/> control.
        /// </summary>
        public ImageBrowser()
        {
            this.DialogTitle = "Browse for image";
            this.ChooseFileButtonCaption = "Browse for image";
            this.ChooseFileButtonImageUrl = "~/images/icon_skins_16px.gif";
            this.DeselectButtonCaption = "No image";
        }

        #endregion

        #region page lifecycle

        /// <summary>
        /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            this.imgPreview = new Image
                                  {
                                      ID = "imgPreview"
                                  };
            this.Controls.Add(this.imgPreview);

            base.CreateChildControls();
        }

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.PreRender"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (this.MaxPreviewWidth.Value > 0)
            {
                this.imgPreview.Style["max-width"] = this.MaxPreviewWidth.ToString(CultureInfo.InvariantCulture);
            }
            if (this.MaxPreviewHeight.Value > 0)
            {
                this.imgPreview.Style["max-height"] = this.MaxPreviewHeight.ToString(CultureInfo.InvariantCulture);
            }
            this.imgPreview.ImageUrl = String.IsNullOrEmpty(this.Text) ? (String.IsNullOrEmpty(this.DefaultPreviewImageUrl)
                ? DefaultPreviewImage : this.DefaultPreviewImageUrl) : this.PortalSettings.HomeDirectory + (this.RootFolder ?? String.Empty) + this.Text;
            
            this.imgPreview.AlternateText = this.Text;
            this.imgPreview.ToolTip = this.Text;

            this.wdlgFileBrowser.ClientEvents.Result += ";jQuery('#" + this.imgPreview.ClientID
                                                        + "').attr('src', ui.dialogResult() ? '"
                                                        + this.PortalSettings.HomeDirectory + (this.RootFolder ?? String.Empty)
                                                        + "' + ui.dialogResult().substring(1) : '"
                                                        + (String.IsNullOrEmpty(this.DefaultPreviewImageUrl)
                                                               ? VirtualPathUtility.ToAbsolute(DefaultPreviewImage)
                                                               : VirtualPathUtility.ToAbsolute(
                                                                     this.DefaultPreviewImageUrl))
                                                        + "').attr('alt', ui.dialogResult() ? ui.dialogResult() : '')"
                                                        + ".attr('title', ui.dialogResult() ? ui.dialogResult() : '')";

            if (this.ShowDeselectButton)
            {
                this.btnDeselect.OnClientClick = "jQuery('#" + this.imgPreview.ClientID + "').attr('src', '"
                                                        + (String.IsNullOrEmpty(this.DefaultPreviewImageUrl)
                                                               ? VirtualPathUtility.ToAbsolute(DefaultPreviewImage)
                                                               : VirtualPathUtility.ToAbsolute(
                                                                     this.DefaultPreviewImageUrl))
                                                        + "');" + this.btnDeselect.OnClientClick;
            }
        }

        #endregion
    }
}
